import { pointApi } from '@/api'
import { useUserStoreHook } from '@/store/modules/userStore'

export interface Point {
  id: number
  parentId: number
  pointName: string
  pointCode?: string
  pointFullName?: string
  children?: Point[] | null
}

export function usePointTree(useCache: boolean = true) {
  const { vLoading, withLoading } = useDefineLoading()

  const treeData = shallowRef<Point[]>([])
  const defaultTreeExpandKeys = ref<number[] | undefined>([])

  const userStore = useUserStoreHook()

  let cache: any = null

  const getTreeData = async (
    needFullName: 0 | 1 = 1,
    callback?: (o: Point[]) => any,
  ) => {
    try {
      let data: any = null
      if (cache && useCache) {
        data = cache
      }
      else {
        const res = await withLoading(
          pointApi.loadRoleEnergyUnit,
        )(needFullName)
        data = cache = res.data
      }
      treeData.value = data.list || []
      userStore.setPointTree(treeData.value)
      if (data.pointIdList === null) {
        defaultTreeExpandKeys.value = findAllIdFromTree(data.list, [])
      }
      else {
        defaultTreeExpandKeys.value = (data.pointIdList || []).map((v: string) => Number(v))
      }
      await nextTick()
      callback?.(data.list || [])
    }
    catch (e) {}
  }

  function findAllIdFromTree(tree: any[], ids: number[]) {
    tree.forEach((item) => {
      ids.push(item.id)
      if (item.children && item.children.length > 0) {
        findAllIdFromTree(item.children, ids)
      }
    })
    return ids
  }

  return {
    treeData,
    defaultTreeExpandKeys,

    vLoading,
    getTreeData,
  }
}

export function useTreeFilter(
  key: string = 'label',
  callback?: (val: string) => any,
) {
  const filterTextInput = ref<string>('')

  const filterNode = (value: string, data: any) => {
    if (!value)
      return true
    return data[key].includes(value)
  }

  watch(
    () => filterTextInput.value,
    (val: string) => {
      callback?.(val)
    },
  )
  return {
    filterTextInput,

    filterNode,
  }
}
